package com.example.myapplication1;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import android.util.Patterns;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import android.util.Log;

import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.utils.PreferenceManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.android.material.textfield.TextInputLayout;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.radiobutton.MaterialRadioButton;

import java.util.regex.Pattern;

public class RegisterActivity extends AppCompatActivity {
    private TextInputLayout usernameLayout;
    private TextInputLayout passwordLayout;
    private TextInputLayout confirmPasswordLayout;
    private TextInputLayout phoneLayout;
    private TextInputEditText usernameInput;
    private TextInputEditText passwordInput;
    private TextInputEditText confirmPasswordInput;
    private TextInputEditText phoneInput;
    private MaterialRadioButton maleRadio;






    private MaterialRadioButton femaleRadio;




    private MaterialCheckBox agreementCheckbox;
    private MaterialButton registerButton;
    private View loadingProgress;
    private View termsLink;
    private View privacyLink;
    private Toolbar toolbar;

    // 用户名格式：4-16位字母、数字、下划线
    private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_]{4,16}$");

    private static final String TAG = "RegisterActivity";

    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        setupToolbar();
        setupClickListeners();

        databaseHelper = new DatabaseHelper(this);
        preferenceManager = new PreferenceManager(this);
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        usernameLayout = findViewById(R.id.usernameLayout);
        passwordLayout = findViewById(R.id.passwordLayout);
        confirmPasswordLayout = findViewById(R.id.confirmPasswordLayout);
        phoneLayout = findViewById(R.id.phoneLayout);
        usernameInput = findViewById(R.id.usernameInput);
        passwordInput = findViewById(R.id.passwordInput);
        confirmPasswordInput = findViewById(R.id.confirmPasswordInput);
        phoneInput = findViewById(R.id.phoneInput);
        maleRadio = findViewById(R.id.maleRadio);
        femaleRadio = findViewById(R.id.femaleRadio);
        agreementCheckbox = findViewById(R.id.agreementCheckbox);
        registerButton = findViewById(R.id.registerButton);
        loadingProgress = findViewById(R.id.loadingProgress);
        termsLink = findViewById(R.id.termsLink);
        privacyLink = findViewById(R.id.privacyLink);

        // 设置用户名输入框的帮助图标点击事件
        usernameLayout.setEndIconOnClickListener(v -> new MaterialAlertDialogBuilder(this)
            .setTitle(R.string.username_rules_title)
            .setMessage(getString(R.string.username_helper))
            .setPositiveButton(R.string.dialog_ok, null)
            .show());
    }

    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("");
        }
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    private void setupClickListeners() {
        registerButton.setOnClickListener(v -> attemptRegister());
        termsLink.setOnClickListener(v -> Toast.makeText(this, R.string.terms_developing, Toast.LENGTH_SHORT).show());
        privacyLink.setOnClickListener(v -> Toast.makeText(this, R.string.privacy_developing, Toast.LENGTH_SHORT).show());
    }

    private void attemptRegister() {
        // 重置错误提示
        usernameLayout.setError(null);
        passwordLayout.setError(null);
        confirmPasswordLayout.setError(null);
        phoneLayout.setError(null);

        // 获取输入内容
        String username = usernameInput.getText().toString().trim();
        String password = passwordInput.getText().toString();
        String confirmPassword = confirmPasswordInput.getText().toString();
        String phone = phoneInput.getText().toString().trim();
        String gender = maleRadio.isChecked() ? "male" : "female";

        Log.d(TAG, "Attempting to register user: " + username);

        // 验证输入
        if (!validateInput(username, password, confirmPassword, phone)) {
            Log.d(TAG, "Input validation failed");
            return;
        }

        // 显示加载动画
        showLoading(true);

        try {
            Log.d(TAG, "Checking if username exists: " + username);
            // 检查用户名是否已存在
            if (databaseHelper.isUsernameExists(username)) {
                showLoading(false);
                usernameLayout.setError(getString(R.string.error_username_exists));
                Log.d(TAG, "Username already exists: " + username);
                return;
            }

            Log.d(TAG, "Adding new user to database");
            // 添加用户到数据库
            registerUser(username, password, phone, gender);
        } catch (Exception e) {
            showLoading(false);
            Log.e(TAG, "Error during registration: " + e.getMessage());
            e.printStackTrace();
            Toast.makeText(this, "注册过程中发生错误", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean validateInput(String username, String password, String confirmPassword, String phone) {
        if (TextUtils.isEmpty(username)) {
            usernameLayout.setError(getString(R.string.error_empty_username));
            return false;
        }

        if (!USERNAME_PATTERN.matcher(username).matches()) {
            usernameLayout.setError(getString(R.string.error_invalid_username));
            return false;
        }

        if (TextUtils.isEmpty(password)) {
            passwordLayout.setError(getString(R.string.error_empty_password));
            return false;
        }

        if (password.length() < 6) {
            passwordLayout.setError(getString(R.string.error_invalid_password));
            return false;
        }

        if (!password.equals(confirmPassword)) {
            confirmPasswordLayout.setError(getString(R.string.error_passwords_not_match));
            return false;
        }

        if (!Patterns.PHONE.matcher(phone).matches()) {
            phoneLayout.setError(getString(R.string.error_invalid_phone));
            return false;
        }

        if (!agreementCheckbox.isChecked()) {
            Toast.makeText(this, R.string.error_must_agree, Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void showLoading(boolean show) {
        loadingProgress.setVisibility(show ? View.VISIBLE : View.GONE);
        registerButton.setEnabled(!show);
        usernameInput.setEnabled(!show);
        passwordInput.setEnabled(!show);
        confirmPasswordInput.setEnabled(!show);
        phoneInput.setEnabled(!show);
        maleRadio.setEnabled(!show);
        femaleRadio.setEnabled(!show);
        agreementCheckbox.setEnabled(!show);
    }

    private void registerUser(String username, String password, String phone, String gender) {
        showLoading(true);
        
        // 在后台线程中执行注册
        new Thread(() -> {
            try {
                // 注册用户并获取用户ID
                long userId = databaseHelper.addUser(username, password, phone, gender);
                
                if (userId != -1) {
                    // 初始化用户信息，包括20元初始余额
                    preferenceManager.initializeNewUser(username, phone, userId);
                    
                    // 在主线程中处理UI更新
                    runOnUiThread(() -> {
                        showLoading(false);
                        Toast.makeText(RegisterActivity.this, "注册成功！初始赠送20元", Toast.LENGTH_SHORT).show();
                        
                        // 返回到登录界面
                        Intent intent = new Intent();
                        intent.putExtra("username", username);
                        setResult(RESULT_OK, intent);
                        finish();
                    });
                } else {
                    runOnUiThread(() -> {
                        showLoading(false);
                        Toast.makeText(RegisterActivity.this, "用户名已存在", Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (Exception e) {
                Log.e(TAG, "Error during registration", e);
                runOnUiThread(() -> {
                    showLoading(false);
                    Toast.makeText(RegisterActivity.this, "注册失败，请重试", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
} 